package cn.hn.java.summer.mvc.tag;


import cn.hn.java.summer.mvc.WebContext;
import org.rythmengine.template.JavaTagBase;
import org.springframework.web.servlet.resource.ResourceUrlProvider;

import javax.servlet.http.HttpServletRequest;

public class ResourceTag extends JavaTagBase
{
  public String __getName()
  {
    return "res";
  }

  private static ResourceUrlProvider resourceUrlProvider;

  protected void call(__ParameterList params, __Body body)
  {
    Object obj = params.getDefault();
    HttpServletRequest request = WebContext.getRequest();
    String contextPath = request.getContextPath();

    if ((obj != null) && ((obj instanceof String))){
      String url = (String)obj;
      //调用ResourceUrlProvider提供的方法查找ResourceHandlerRegistry中注册的资源
      //返回文件名+文件内容md5格式的资源链接
      url=resourceUrlProvider.getForLookupPath(url);
      if ((url.startsWith("http")) || (url.startsWith("//"))) {
        p(url);
      }else{
        p(contextPath + url);
      }
    }
  }

  /**
   * 设置resourceUrlProvider
   * @param resourceUrlProvider
   */
  public static void setResourceUrlProvider(ResourceUrlProvider resourceUrlProvider) {
    if(ResourceTag.resourceUrlProvider==null) {
      ResourceTag.resourceUrlProvider = resourceUrlProvider;
    }
  }

}